package com.binance.gateway.ua;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class CachingParser extends Parser {

    private static final int CACHE_SIZE = 2000;

    private LoadingCache<String, Client> cacheClient = null;

    public CachingParser() {
        super();
    }

    @Override
    public Client parse(String agentString) {
        if (agentString == null) {
            return null;
        }
        if (cacheClient == null) {
            cacheClient = CacheBuilder.newBuilder()
                    .maximumSize(CACHE_SIZE)
                    .expireAfterAccess(60, TimeUnit.MINUTES)
                    .removalListener((RemovalListener<String, Client>) notification -> {
                        log.info("cacheClient removed key:{}", notification.getKey());
                    })
                    .recordStats()
                    .build(new CacheLoader<String, Client>() {
                        @Override
                        public Client load(String key) {
                            return superClient(key);
                        }
                    });
        }
        Client client = cacheClient.getIfPresent(agentString);
        if (client != null) {
            return client;
        }
        client = super.parse(agentString);
        cacheClient.put(agentString, client);
        return client;
    }

    private Client superClient(String agentString) {
        return super.parse(agentString);
    }
}
